package com.chen.day01_base;

public class VolatileExample {
    // volatile 关键字保证了 flag 变量的可见性
    private volatile boolean flag = false;

    public void method1() {
        System.out.println("Thread1 started");
        while (!flag) {
            // 线程1 在此处等待 flag 变为 true
        }
        System.out.println("Thread1 finished");
    }

    public void method2() {
        System.out.println("Thread2 started");
        flag = true;  // 修改 flag 为 true
        System.out.println("Thread2 finished");
    }

    public static void main(String[] args) throws InterruptedException {
        VolatileExample example = new VolatileExample();

        Thread t1 = new Thread(example::method1);
        Thread t2 = new Thread(example::method2);

        t1.start();
        Thread.sleep(1000);  // 确保 t1 线程先执行
        t2.start();
    }
}
